package com.muapet.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.muapet.model.Pet;
import com.muapet.model.User;
import com.muapet.model.Variety;
import com.muapet.model.other.PetCondition;
import com.muapet.service.IPetService;
import com.muapet.service.IUserService;
import com.muapet.util.MyFileUpload;
import com.muapet.util.constants.MyConstants;

@Controller
@RequestMapping("/pet")
public class PetController {
	private IPetService petService;
	private IUserService userService;

	@Autowired
	public void setPetService(IPetService petService) {
		this.petService = petService;
	}

	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@RequestMapping("/searchPet")
	public ModelAndView searchPet(String title) {
		ModelAndView mav = new ModelAndView("searchPet");
		mav.addObject("title", title);
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listPetByConditions")
	@ResponseBody
	public String listPetByConditions(PetCondition conditions) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<Pet> petList = petService.listPetByConditions(conditions);
			Integer total = petService.countPetByConditions(conditions);
			resultMap.put("msg", "success");
			resultMap.put("petList", petList);
			resultMap.put("total", total);
		} catch (Exception e) {
			resultMap.put("msg", "error");
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping("/myPets")
	public ModelAndView myPets() {
		ModelAndView mav = new ModelAndView("myPets");
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listPetBySelf")
	@ResponseBody
	public String listPetBySelf(HttpServletRequest request, Integer state) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			User loginUser = (User) request.getSession().getAttribute(
					"loginUser");
			if (loginUser == null) {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "请登录后重试！");
			} else {
				List<Pet> petList = petService.listPetBySeller(
						loginUser.getId(), state);
				resultMap.put("msg", "success");
				resultMap.put("petList", petList);
				return JSON.toJSONString(resultMap);
			}
		} catch (Exception e) {
			resultMap.put("msg", "error");
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping("/hisPets")
	public ModelAndView hisPets(HttpServletRequest request, Integer id) {
		ModelAndView mav;
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser != null && loginUser.getId().equals(id)) {
			return myPets();
		}
		User user = userService.findShowUserById(id);
		if (user == null) {
			mav = new ModelAndView("error");
			mav.addObject("msg", "找不到用户");
		} else {
			mav = new ModelAndView("hisPets");
			mav.addObject("user", user);
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listPetByUser")
	@ResponseBody
	public String listPetByUser(Integer id, Integer state) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Pet> petList = petService.listPetBySeller(id, state);
		resultMap.put("msg", "success");
		resultMap.put("petList", petList);
		return JSON.toJSONString(resultMap);
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listNewestPet")
	@ResponseBody
	public String listNewestPet() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<Pet> petList = petService.listNewestPet();
			resultMap.put("msg", "success");
			resultMap.put("petList", petList);
		} catch (Exception e) {
			resultMap.put("msg", "error");
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/listVarietysByType")
	@ResponseBody
	public String listVarietysByType(Integer type) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<Variety> varietyList = petService.listVarietysByType(type);
			resultMap.put("msg", "success");
			resultMap.put("varietyList", varietyList);
		} catch (Exception e) {
			resultMap.put("msg", "error");
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping(path = "/newPet")
	public ModelAndView newPet() {
		ModelAndView mav = new ModelAndView("addPet");
		return mav;
	}

	@RequestMapping(path = "/editPet")
	public ModelAndView editPet(Integer pet_id, HttpServletRequest request) {
		Pet pet = petService.findById(pet_id);
		ModelAndView mav;
		if (pet != null) {
			User loginUser = (User) request.getSession().getAttribute(
					"loginUser");
			if (loginUser != null
					&& loginUser.getId().equals(pet.getSellerId())) {
				mav = new ModelAndView("addPet");
				mav.addObject("editingPet", pet);
			} else {
				mav = new ModelAndView("error");
				mav.addObject("msg", "不是自己的宠物不能修改哦！");
			}
		} else {
			mav = new ModelAndView("error");
			mav.addObject("msg", "找不到宠物信息！");
		}
		return mav;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/addPet")
	@ResponseBody
	public String addPet(Pet pet, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Pet oldPet = petService.findById(pet.getId());
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if (loginUser == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "请先登录！");
		} else if (userService.findAccountByUserId(loginUser.getId()) == null) {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "还未开通我的钱包，不能发布宠物信息！");
		} else {
			if (oldPet != null) {
				if (loginUser != null
						&& loginUser.getId().equals(oldPet.getSellerId())) {
					if (oldPet.getBuyerId() == null || oldPet.getBuyerId() == 0) {
						petService.update(pet);
						resultMap.put("msg", "success");
					} else {
						resultMap.put("msg", "error");
						resultMap.put("errorMsg", "已售出宠物不能修改哦！");
					}
				} else {
					resultMap.put("msg", "error");
					resultMap.put("errorMsg", "不是自己的宠物不能修改哦！");
				}
			} else {
				pet.setSellerId(loginUser.getId());
				pet.setSellerName(loginUser.getName());
				petService.add(pet);
				resultMap.put("msg", "success");
				resultMap.put("petId", pet.getId());
			}
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping(path = "/showPetDetail")
	public ModelAndView showPetDetail(Integer id) {
		Pet pet = petService.findById(id);
		if (pet != null) {
			User seller = userService.findShowUserById(pet.getSellerId());
			ModelAndView mav = new ModelAndView("petDetail");
			mav.addObject("seller", seller);
			mav.addObject("pet", pet);
			return mav;
		} else {
			ModelAndView mav = new ModelAndView("error");
			mav.addObject("msg", "找不到该宠物详情");
			return mav;
		}
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, method = RequestMethod.POST, path = "/deletePet")
	@ResponseBody
	public String deletePet(Integer pet_id, HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Pet pet = petService.findById(pet_id);
		if (pet != null) {
			User loginUser = (User) request.getSession().getAttribute(
					"loginUser");
			if (loginUser != null
					&& loginUser.getId().equals(pet.getSellerId())) {
				if (pet.getBuyerId() != null && pet.getBuyerId() != 0) {
					resultMap.put("msg", "error");
					resultMap.put("errorMsg", "已出售的宠物不能删除哦！");
				} else {
					petService.delete(pet.getId());
					resultMap.put("msg", "success");
				}
			} else {
				resultMap.put("msg", "error");
				resultMap.put("errorMsg", "不是自己的宠物不能删除哦!");
			}
		} else {
			resultMap.put("msg", "error");
			resultMap.put("errorMsg", "找不到宠物信息！请刷新界面!");
		}
		String result = JSON.toJSONString(resultMap);
		return result;
	}

	@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE, path = "/saveImage")
	@ResponseBody
	public String saveImage(MultipartFile userIcon, HttpServletRequest request) {
		String iconURL = new MyFileUpload().writeImg(userIcon,
				MyConstants.PET_ICON_BASE_URL);
		return JSON.toJSONString(iconURL);
	}

	@RequestMapping(path = "/buyPet")
	public ModelAndView buyPet(Integer id) {
		Pet pet = petService.findById(id);
		if (pet != null) {
			ModelAndView mav = new ModelAndView("newOrder");
			mav.addObject("pet", pet);
			return mav;
		} else {
			ModelAndView mav = new ModelAndView("error");
			mav.addObject("msg", "找不到该宠物");
			return mav;
		}
	}
}
